//
//  WZLChatViewController.m
//  coreDataToChat
//
//  Created by WangZe on 15/11/24.
//  Copyright © 2015年 王泽龙. All rights reserved.
//

#import "WZLChatViewController.h"
#import "WZLChatCell.h"
#import "Message.h"
#import "WZLCoreDataToChatManager.h"
#import "WZLRoster.h"
#import "NetworkHandler.h"
@interface WZLChatViewController ()

@property(nonatomic, strong)NSArray *messageArr;

@property(nonatomic, strong)WZLCoreDataToChatManager *manager;


@end

@implementation WZLChatViewController


// storyboard初始方法
- (void)awakeFromNib
{
    self.manager = [WZLCoreDataToChatManager shareWZLCoreDataToChatManager];
    
    // 添加一个监听,看看有没有收到消息 发送消息 来进行界面刷新
    // 监听receive事件 如果触发 就触发reloadMessage方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMessage) name:@"receive" object:nil];
    NSLog(@"%@", [self.manager applicationDocumentsDirectory]);
}
- (void)reloadMessage
{
    self.messageArr = [self.manager selectMessageWithFormat:[NSString stringWithFormat:@"from = '%@' OR to = '%@'", self.roster.name, self.roster.name]];
    
    [self.tableView reloadData];
    
    if (self.messageArr.count!= 0) {
        
        
        // 滚动到最后一行
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageArr.count - 1 inSection:0];
        //以动画的方式滚动到最后一行
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        
    }
}



- (IBAction)sendMessage:(UIBarButtonItem *)sender {
    NSString *mes = @"SB书华";
    NSString *from = @"刘超";
    
    // 先存到本地
    [self.manager addMessage:mes fromName:from toName:self.roster.name];
    [self reloadMessage];
    
    
    NSString *sendUrl = [NSString stringWithFormat:@"http://172.16.5.38/getui/demo.php?token=%@token&name=%@&message=%@", self.roster.token, from, mes];
    
    [NetworkHandler connectNetGetDataWithURLString:sendUrl complention:^(id result) {
        NSLog(@"发送成功");
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self.tableView registerClass:[WZLChatCell class] forCellReuseIdentifier:@"reuse"];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.messageArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WZLChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    
    Message *message = self.messageArr[indexPath.row];
    
    // 判断消息来源
    // 如果是好友发送来的,左边显示消息内容,右边显示时间
    // 如果是自己发送的,左边显示时间,右边显示消息内容
    // 左边按钮和右边按钮
    if ([message.from isEqualToString:self.roster.name]) {
        cell.rightLabel.text = message.mes;
        cell.leftLabel.text = message.time;
    }
    else
    {
        cell.leftLabel.text = message.time;
        cell.rightLabel.text = message.mes;
    }
    
    
    
    
    
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
